iT邦幫忙

2025 iThome 鐵人賽

DAY 6
0
DevOps

DevOps 進化論:從全能型戰士到安全守門員系列 第 6

Day 6:測試自動化(Unit Test + Integration Test)

  • 分享至 

  • xImage
  •  

●前言
上一篇已經成功在Github上面建立一個簡單的CI pipeline,這一篇把測試導入工作流程,使用GitHub Actions機制達成測試自動化的效果

● 目標
1.建立單元測試、整合測試,並返回覆蓋率測試結果
2.完成測試自動化,推送至GitHub時,即觸發包含測試的工作流程

● 單元測試 vs 整合測試
https://ithelp.ithome.com.tw/upload/images/20250819/20178156sIrK3jZCRx.png

● 專案目錄
https://ithelp.ithome.com.tw/upload/images/20250819/20178156z3cPZDfsfE.png

● 實作步驟(沿用上一篇的專案目錄進行小幅度調整)
1.建立專案所需檔案
https://ithelp.ithome.com.tw/upload/images/20250819/20178156PjyBXULvbb.png
https://ithelp.ithome.com.tw/upload/images/20250819/20178156iY12npK5PP.png
▪建立main.py、utils.py、test_utils.py以及test_api.py作為本次測試的基本檔案
▪在專案中建立資料夾 .github/workflows/,並新增檔案 ci.yml。

2.安裝套件先在本機進行測試
https://ithelp.ithome.com.tw/upload/images/20250819/201781561nDRtZL58w.png

3.初始化 Git、切至 main 分支、綁定 repo
https://ithelp.ithome.com.tw/upload/images/20250819/20178156ziD6RHTit6.png
▪git init : 初始化
▪git branch -M main:改名並切至main
▪git remote add origin : url替換成該repo的url

4.加入暫存區、提交並上版
https://ithelp.ithome.com.tw/upload/images/20250819/20178156tb1nof9JwA.png
▪git add . → git commit -m "add ci pipeline" → git push -u origin main。

5.檢視結果
https://ithelp.ithome.com.tw/upload/images/20250819/201781561LBvUSWc9y.png
▪到 GitHub Repo → Actions 分頁,就能看到 pipeline 自動執行。
✅如果測試成功,會看到綠色的「✔ Passed」。
❌如果失敗,GitHub 會顯示錯誤訊息,幫助你排查問題。

● 注意事項
▪測試檔案要放在 tests/ 目錄下,並以 test_*.py 命名,pytest 才能自動找到。
▪app/ 目錄內要有 init.py,否則會出現 ModuleNotFoundError: No module named 'app'。
▪在 GitHub Actions 內建環境跑測試時,務必設定 PYTHONPATH=. 或使用 pip install -e .,否則無法匯入模組。
▪如果測試失敗,GitHub Actions 的 log 會清楚標示是哪個測試掛掉,可據此回頭 debug。

● 總結
▪Unit Test 專注在驗證單一函式/模組,快速而精準。
▪Integration Test 模擬實際運作情境,確保系統元件能協同工作。
▪搭配 pytest + pytest-cov,我們能同時獲得測試結果與覆蓋率報告。
▪透過 GitHub Actions,每一次 push/PR 都會觸發測試,確保程式碼隨時保持穩定。

👉 下一篇將進一步介紹 效能測試與簡單報表,讓測試從正確性走向效能與穩定性。


上一篇
Day 5:建立簡易的CI pipeline (GitHub Actions)
下一篇
Day 7:測試策略與效能測試概念
系列文
DevOps 進化論:從全能型戰士到安全守門員19
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言